class AdminController < ApplicationController
  before_filter :authorize_admin

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [:destroy_user, :create_user, :update_user],
    :redirect_to => {:action => :list}

  def index
  end

  def countries_list
    @countries = Country.find(:all)
  end

  def upload_image
    country = Country.find(params[:id])
    success = country.update_attributes(params[:country_item])
    set_flash_info success \
      ? FlashInfo.get_notice("Image has been successfully updated.") \
      : FlashInfo.get_error("Image could not be updated.")
    redirect_to :action => :countries_list
  end
  
  def remove_image
    country = Country.find(params[:id])
    success = country.update_attribute(:image_url, nil)
    set_flash_info success \
      ? FlashInfo.get_notice("Image has been removed successfully.") \
      : FlashInfo.get_error("Image could not be removed.")
    redirect_to :action => :countries_list
  end

  def users_list
    @users = User.find(:all, :conditions => ["login != ?", SUPERADMIN_LOGIN])
  end

  def new_user
    @user = User.new(:user_type_id => UserType::STUDENT[:id])
  end

  def create_user
    password = PasswordGenerator.generate
    params[:user][:password] = password
    @user = User.new(params[:user])

    if @user.save
      set_flash_info(FlashInfo.get_notice("User was successfully added."))
      NewUser.deliver_new_user(@user, password)
    else
      set_flash_info(FlashInfo.get_error("User could not be added."))
    end
    
    redirect_to :action => :users_list
  end
  
  def edit_user
    @user = User.find(params[:id])
  end
  
  def update_user
    @user = User.find(params[:id])
    
    set_flash_info @user.update_attributes(params[:user]) \
      ? set_flash_info(FlashInfo.get_notice("User was successfully updated.")) \
      : set_flash_info(FlashInfo.get_error("User could not be updated."))

    redirect_to :action => :users_list
  end
  
  def destroy_user
    if User.exists?(params[:id])
      User.find(params[:id]).destroy
    end
    redirect_to :action => :users_list
  end
end